import store from '@/utils/login.js';

const request = async (params) => {
	const config = {
		url: '',
		data: {},
		header: {},
		method: 'GET',
	};
	for (let key in params) {
		config[key] = params[key];
	}
	
	config.header.token = store.state?.data?.token || '';
	config.method = config.method.toUpperCase();
	let [err, res] = await uni.request(config);
	let response = getResponse(err, res);
	responseException(response);
	return response;
};

function getResponse(err, res) {
	let response = {status: 200, msg: 'ok', data: null};
	if (err !== null) {
		response.status = 0;
		response.msg = err.errMsg || '系统错误';
	} else {
		try{
			if (res.data !== JSON.parse(res.data)) {
				res.data = JSON.parse(res.data);
			}
		} catch(e){
			//TODO handle the exception
		}
		if (res.statusCode === 200) {
			response = res.data;
		} else {
			if (typeof res.data === 'object' && Object.prototype.toString.call(res.data) === "[object Object]" && JSON.stringify(res.data) !== '{}' && Object.keys(res.data).length > 0) {
			    response = res.data;
			} else {
			    response.status = res.statusCode;
				response.msg = res.data;
			}
		}
	}
	return response;
}

function responseException(response) {
	if (response.status === 100) {
		store.commit('logout');
		uni.reLaunch({
			url: '/pages/login/index'
		});
		throw new Error(response.msg);
	}
	
	if (response.status !== 200) {
		uni.showToast({
			title: response.msg,
			icon: 'none'
		});
		throw new Error(response.msg);
	}
}

export function requestGet(url, data = {}) {
	return request({
		url,
		data,
		method: 'GET'
	});
};

export function requestPost(url, data = {}) {
	return request({
		url,
		data,
		method: 'POST'
	});
};

export function requestDelete(url, data = {}) {
	return request({
		url,
		data,
		method: 'DELETE'
	});
};

export function requestPut(url, data = {}) {
	return request({
		url,
		data,
		method: 'PUT'
	});
};

export async function requestUpload(url, files, formData = {}, header = {}) {
	header.token = store.state?.data?.token || '';
	if (Object.prototype.toString.call(files) === '[object String]') {
		files = [{name: 'file', file: files}];
	} else if (Object.prototype.toString.call(files) === '[object Object]') {
		files = [files];
	}
	files = files.map(item => {
		item.uri = item.file;
		return item;
	});
	let [err, res] = await uni.uploadFile({
		url,
		files,
		formData,
		header
	});
	let response = getResponse(err, res);
	responseException(response);
	return response;
}

export async function requestDownload(url, header = {}) {
	header.token = store.state?.data?.token || '';
	let [err, res] = await uni.downloadFile({
		url,
		header
	});
	if (err) {
		uni.showToast({
			title: err.errMsg,
			icon: 'none'
		});
		return null;
	}
	if (res.statusCode !== 200) {
		uni.showToast({
			title: '下载失败',
			icon: 'none'
		});
		return null;
	}
	return res.tempFilePath;
}